from blog.models import MiniPost, ResultSet, StaticPage, Project, FileInfo
from django.core.paginator import ObjectPaginator, InvalidPage
from google.appengine.api import datastore_errors
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.blobstore import BlobInfo
from google.appengine.ext.db import Model
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from pyamf import amf3
from pyamf.remoting.gateway.google import WebAppGateway
import logging
import os
import pyamf

AMF_NAMESPACE = "org.flexspeedup.blog.models"
PAGE_SIZE = 10
FILE_SERVE_PATH = '/assets/'

def echo(data):
    return 'PyAMF says: ' + data

def save_static_page(page, page_name):
    """saves / updates a static page in the datastore"""
    new_page = StaticPage.get_or_insert(page_name)
    new_page.body = page.body
    new_page.title = page.title
    new_page.put()
    return new_page

def get_static_page(page_name):
    """retrieves a StaticPage by key_name"""
    return StaticPage.get_by_key_name(page_name)

def save_post(post):
    post.put()
    return post
    
def create_post(post):
    return save_post(
        MiniPost(
            body = post.body, 
            title = post.title,
            category = post.category,
            )
        )

def delete_post(post):
    post.delete()
    
def get_posts(page, page_size=None, category=None):
    query = MiniPost.all().order('-date')
    if category: query = query.filter('category =', category)
    return paginate_query(query, page, page_size)

def get_files(page, page_size=None):
    query = BlobInfo.all().order('-filename')
    resultSet = paginate_query(query, page, page_size)
    files = []
    for item in resultSet.items:
        file = FileInfo()
        file.filename = item.filename
        file.uri = FILE_SERVE_PATH + str(item.key())
        files.append(file)
    resultSet.items = files
    return resultSet

def get_projects(page, page_size=None):
    query = Project.all().order('-date')
    return paginate_query(query, page, page_size)

def get_all_projects():
    return Project.all().order('-date')
    
def create_project(project):
    return save_project(
        Project(
            title = project.title,
            imageFilename = project.imageFilename,
            imageUri = project.imageUri,
            thumbnailFilename = project.thumbnailFilename,
            thumbnailUri = project.thumbnailUri,
        )
    )
    
def save_project(project):
    project.put()
    return project
    
def delete_project(project):
    project.delete()
    
def paginate_query(query, page, page_size=None):
    paginator = ObjectPaginator(query, page_size or PAGE_SIZE)
    paginator_page = page - 1
    resultSet = ResultSet()
    resultSet.hasNextPage = paginator.has_next_page(paginator_page)
    resultSet.hasPreviousPage = paginator.has_previous_page(paginator_page)
    if resultSet.hasNextPage:
        resultSet.nextPage = page + 1
    if resultSet.hasPreviousPage:
        resultSet.previousPage = page - 1
    resultSet.itemCountPerPage = PAGE_SIZE
    resultSet.totalItemCount = paginator.hits
    resultSet.pageCount = paginator.pages
    resultSet.currentPage = page
    resultSet.items = paginator.get_page(paginator_page)
    return resultSet    

def logout():
    return users.create_logout_url('/admin')
    
def get_current_user():
    """returns the current authenticated user"""
    return users.get_current_user().nickname()

def main():    
    debug = True
    logging.getLogger().setLevel(logging.DEBUG)

    pyamf.register_class(MiniPost, '%s.MiniPost' % AMF_NAMESPACE)
    pyamf.register_class(ResultSet, '%s.ResultSet' % AMF_NAMESPACE)
    pyamf.register_class(StaticPage, '%s.StaticPage' % AMF_NAMESPACE)
    pyamf.register_class(Project, '%s.Project' % AMF_NAMESPACE)
    pyamf.register_class(FileInfo, '%s.FileInfo' % AMF_NAMESPACE)

    services = {
        'services.echo' : echo,
        'services.savePost' : save_post,
        'services.createPost' : create_post,
        'services.getPosts' : get_posts,
        'services.logout' : logout,
        'services.getCurrentUser' : get_current_user,
        'services.deletePost': delete_post,
        'services.saveStaticPage' : save_static_page,
        'services.getStaticPage' : get_static_page,
        'services.getProjects' : get_projects,
        'services.getFiles' : get_files,
        'services.saveProject' : save_project,
        'services.createProject' : create_project,
        'services.deleteProject' : delete_project,
        'services.getAllProjects' : get_all_projects,
    }

    gateway = WebAppGateway(services, logger = logging, debug = debug)

    paths = [
        ('/gateway', gateway),
    ]

    application = webapp.WSGIApplication(paths, debug = debug)
    util.run_wsgi_app(application)
    
if __name__ == '__main__':
    main()
    
